package com.cz.background.common.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.hutool.core.util.StrUtil;
import com.cz.background.common.dto.ResponseResult;
import com.cz.background.common.exception.BizException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(NotLoginException.class)
    public ResponseEntity<ResponseResult> handleException(NotLoginException nle) {
        String message = "";
        if(nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            message = "未能读取到有效 token";
        }
        else if(nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "token 无效";
        }
        else if(nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            message = "token 已过期";
        }
        else if(nle.getType().equals(NotLoginException.BE_REPLACED)) {
            message = "token 已被顶下线";
        }
        else if(nle.getType().equals(NotLoginException.KICK_OUT)) {
            message = "token 已被踢下线";
        }
        else if(nle.getType().equals(NotLoginException.TOKEN_FREEZE)) {
            message = "token 已被冻结";
        }
        else if(nle.getType().equals(NotLoginException.NO_PREFIX)) {
            message = "未按照指定前缀提交 token";
        }
        else {
            message = "当前会话未登录";
        }
       return  ResponseEntity.status(401).body(ResponseResult.failure(message,null));
    }

    @ExceptionHandler(BizException.class)
    public ResponseEntity<ResponseResult> handleException(BizException bizException){
        return ResponseEntity.status(500).body(ResponseResult.failure(bizException.getErrorMessage(),null));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ResponseResult> handleException(Exception e){
        logger.error(e.getMessage(),e);
        return ResponseEntity.status(500).body(ResponseResult.failure("系统内部错误",null));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ResponseResult> HandlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        Object[] args = e.getDetailMessageArguments();
        String message = Arrays.stream(args).filter(arg -> StrUtil.isNotEmpty(arg.toString())).map(arg -> arg.toString()).collect(Collectors.joining(","));
        return ResponseEntity.status(500).body(ResponseResult.failure(message, null));
    }
}
